#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTcpSocket>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <QAndroidJniObject>
#include <QAndroidJniEnvironment>
#include "ffmpeg/ffmpeg_impl.h"
#include "logicimpl.h"
#include <QFile>
#include <QDataStream>
#include <QImage>
#include <QPainter>
#include <qDebug>
#include <QDateTime>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    buf_show(0,0)
{
    ui->setupUi(this);
    mImpl  = new LogicImpl(this);

    mImpl->Init();
    //m_nTimerId = startTimer(50);
  // int g_epollFd = epoll_create(1000);
  //  QTcpSocket TcpSocket(this);
    //TcpSocket.connect()
}

MainWindow::~MainWindow()
{
   if ( m_nTimerId != 0 )
      killTimer(m_nTimerId);

   delete mImpl;

   delete ui;
}

void MainWindow::add_rgb_buf(const CStreamBuf &buf)
{
    {
        CCriticalAutoLock loAutoLock(oCriSection);
        all_rgb_buf.push(buf);
    }
    update();
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    QMainWindow::timerEvent(event);

    QDateTime time;

    time = QDateTime::currentDateTime();
    qDebug(QString("Timer1:").append(time.toString("yyyy-MM-dd hh:mm:ss")).toLocal8Bit().data());
    //qDebug(QString("xxxxxx11111").toLocal8Bit().data());

    {
      CCriticalAutoLock loAutoLock(oCriSection);
      buf_show = all_rgb_buf.front();
      all_rgb_buf.pop();
    }


    update();

    time = QDateTime::currentDateTime();
    qDebug(QString("Timer3:").append(time.toString("yyyy-MM-dd hh:mm:ss")).toLocal8Bit().data());
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QMainWindow::paintEvent(event);

    QPainter painter( this );

    if(!all_rgb_buf.empty())
    {
      CCriticalAutoLock loAutoLock(oCriSection);
      buf_show = all_rgb_buf.front();
      all_rgb_buf.pop();
      //qDebug(QString("all_rgb_buf.front()...").toLocal8Bit().data());
    }
    unsigned char* ptr = (unsigned char*)buf_show.Buf();
    if(buf_show.Len())
    {
        //qDebug(QString("paintEvent... :").append(QString::number((long)buf_show.Len())).toLocal8Bit().data());
        QRect rc = QRect(0,200,640,480);
        painter.drawImage(rc,(QImage(ptr,640,480,QImage::Format_RGB888)));
    }

}

void MainWindow::on_pushButton_2_clicked()
{
    //p_File->open(QFile::ReadOnly);

    //m_FileArray = p_File->readAll();

      //  Init()
    //m_nTimerId = startTimer(50);
}

void MainWindow::on_pushButton_clicked()
{
    if ( m_nTimerId != 0 )
    {
        killTimer(m_nTimerId);
        m_nTimerId = 0;
    }
}
